<template>
<sm-web-map @load="mapLoad" :map-options="mapOptions">
    <Jurisdiction @onTask="getTaskModel" @sendsetFilterProperty="setFilterProperty" :map="map" />
    <LeftToolbar :map="map" :center="center" @on-setLayer="getLayer" @sendSetLevel="setLevel"></LeftToolbar>
    <!-- 点击图斑弹出 -->
    <Search />

<el-dialog title="图斑信息-地塘块信息" :visible.sync="LandParcelInfoVisible" width="75%">
    <PlotMsg :LandParcelInfo="LandParcelInfo" :type="true" :subjectData="subjectData"  @on-location="getLandLocation" />
</el-dialog>

    <Jurisdiction @sendsetFilterProperty="setFilterProperty" :map="map" />
    <sm-scale :position="position"></sm-scale>
    <!-- <sm-mini-map :position="position"></sm-mini-map> -->
    <!-- <sm-tdt-search :position="position" :collapsed="true" :data="tk"></sm-tdt-search> -->
    <sm-tdt-map-switcher :position="position" :data="tk" :collapsed="true"></sm-tdt-map-switcher>
    <sm-zoom :show-zoom-slider="false" :position="position"></sm-zoom>
    <sm-measure headerName="测量框选" :collapsed="true" :position="position" @click.native="experimentalDataAreaLayer"></sm-measure>
    <sm-compass :position="position"></sm-compass>
    <!-- <sm-tdt-route :position="position" :data="tk"></sm-tdt-route> -->
    <sm-coordinate-conversion :position="position" :collapsed="true" :showLocation="true"></sm-coordinate-conversion>

    <el-dialog title="批量编辑" :visible.sync="handleEditVisible" width="80%">
        <el-card shadow="never">
            <el-form ref="form" :model="audit" label-width="120px" label-position="top">
                <el-form-item label="地块类型">
                    <el-cascader v-model="LandParcelInfo.landType" :options="cascaderOptionsOne" @change="handleChange" style="width: 100% !important">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="农产品分类">
                    <el-cascader v-model="LandParcelInfo.landProduct" :options="cascaderOptionsTwo" filterable @change="handleChangeTwo" style="width: 100% !important">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="品种">
                    <el-input type="text" v-model="LandParcelInfo.landProduce"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-row>
                        <el-col :span="24">
                            <el-card>
                                <div slot="header" class="flex">
                                    <span>关联主体</span>
                                    <addSubject style="float: right" :addType="1" :landCodeT="landCodeArray" @click.native="toAddSubject" @on-click="reloadSubject">经营主体</addSubject>
                                </div>
                                <el-table :data="subjectData" border style="width: 100%">
                                    <el-table-column prop="subjectName" label="主体名称" width="180">
                                    </el-table-column>
                                    <el-table-column prop="subjectBase" label="基地" width="180">
                                    </el-table-column>
                                    <el-table-column prop="lsSubjectUseArea" label="占地面积（亩）">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.lsSubjectUseArea"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="lsYearValue" label="年产值(万元)">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.lsYearValue"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column style="display: none" prop="address" label="操作">
                                        <template slot-scope="scope" v-if="landCodeArray.length">
                                            <el-link type="primary" @click="removeSubjectData(scope.row)">删除</el-link>
                                        </template>

                                        <template slot-scope="scope" v-else>
                                            <el-link type="primary" style="margin-right: 20px" @click="editShow(scope.row)">编辑</el-link>
                                            <el-link type="primary" @click="editShow(scope.row)">删除</el-link>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-card>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item style="display: none">
                    <el-button type="primary" @click="BatchEdit">批量编辑</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </el-dialog>

    <el-dialog title="批量审核" :visible.sync="handleAuditVisible">
        <el-card shadow="never">
            <el-form ref="form" :model="audit" label-width="120px">
                <el-form-item label="审核状态">
                    <el-select v-model="audit.value" placeholder="请选择">
                        <el-option v-for="item in auditOptions" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="审核意见">
                    <el-input type="textarea" placeholder="请输入审核意见(允许为空)" v-model="audit.textarea"></el-input>
                </el-form-item>
                <el-form-item style="display: none">
                    <el-button type="primary" @click="BatchReview">批量审核</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </el-dialog>

    <el-dialog title="查看图斑数据" :visible.sync="mapListdialogTableVisible" width="70%">
        <el-button type="primary" style="display: none" size="small" @click="handleEdit">批量编辑</el-button>
        <el-button type="primary" style="display: none" size="small" @click="handleAudit">批量审核</el-button>

        <el-table ref="multipleTable" :data="mapList" tooltip-effect="dark" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" style="display: none">
            </el-table-column>
            <el-table-column property="landId" label="图斑ID" width="150"></el-table-column>
            <el-table-column property="landName" label="地塘块命名" width="180"></el-table-column>
            <el-table-column property="landTownName" label="镇街" width="100"></el-table-column>
            <el-table-column property="landVillageName" label="村居" width="100"></el-table-column>
            <el-table-column property="landTypeName" label="类型" width="100"></el-table-column>
            <el-table-column property="landProductName" label="农产品分类" width="180"></el-table-column>
            <el-table-column property="landProduce" label="作物" width="100"></el-table-column>
            <el-table-column property="landProductArea" label="面积(亩)" width="100"></el-table-column>
            <el-table-column property="subjectNames" label="所属主体"></el-table-column>
            <!-- <el-table-column fixed="right" label="操作" width="200">
          <template slot="header">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit"
              >批量编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleAudit"
              >批量审核</el-button
            >
          </template>

          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleClick(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="handleClick(scope.row)"
              >审核</el-button
            >
          </template>
        </el-table-column> -->
        </el-table>
    </el-dialog>
</sm-web-map>
</template>

<script>
const mapsettings = require("@/mapsettings.js");
let {
    serverUrl,
    tiandituUrl,
    gisUrl,
    dark,
    fillcolor,
    linecolor,
    tiandituToken,
    center,
    zoom,
} = mapsettings;
import Search from "./Search/Search.vue";
import axios from "axios";
import {
    convertKey
} from "@/library";
import {
    mapState
} from "vuex";
// import MapTask from './mixin/MapTask'
// const filter = ["==", "镇街", this.$store?.currentTask?.Task?.value?.administrativeName || '']
// import AddSubject from './PlotMsg/addSubject/addSubject.vue'
export default {
    props: ["filterMapSuccessObj", "random"],
    name: "CreateMap",
    components: {
        Search,
        AddSubject: () => import("./PlotMsg/addSubject/addSubject"),
        PlotMsg: () => import("./PlotMsg/PlotMsg"),
        LeftToolbar: () => import("./LeftToolbar/LeftToolbar"),
        Jurisdiction: () => import("./Jurisdiction/Jurisdiction"),
    },
    watch: {
        // filterMapSuccessObj() {
        //     if (this.filterMapSuccessObj.title && this.filterMapSuccessObj.value) {
        //         if (this.filterMapSuccessObj.title === 'townsValue' && this.filterMapSuccessObj.value === '全部') {
        //             this.localDataBase = []
        //         }
        //     }
        // },
        // filterObj() {
        //     if (this.filterObj.title && this.filterObj.value) {
        //         if (this.filterObj.title === 'townsValue' && this.filterObj.value === '全部') {
        //             this.localDataBase = []
        //         }
        //     }
        // },
        currentTask() {
            this.LandParcelInfoVisible = false;
            if (!localStorage.getItem('currentTask/setCurrentTask')) {

                const loading = this.$loading({
                    lock: true,
                    text: "正在退出任务模式",
                    spinner: "el-icon-loading",
                    background: "rgba(0, 0, 0, 0.7)",
                });

                setTimeout(() => {
                    this.localDataBase = [];
                    this.currentTask = []
                    this.filterObj = {
                        townsValue: "全部",
                        streetsValue: "全部",
                        figureTypeValue: "全部",
                    }
                    this.mapFilter();
                    loading.close();
                }, 2000);

            } else {
                let arr = [];
                this.currentTask.treeData.list.forEach((element) => {
                    if (element.administrativeCode.length > 9) {
                        arr.push(element.administrativeName);
                    }
                });
                const loading = this.$loading({
                    lock: true,
                    text: "正在搜索图斑数据,请耐心等待",
                    spinner: "el-icon-loading",
                    background: "rgba(0, 0, 0, 0.7)",
                });
                setTimeout(() => {
                    let params = {
                        "collectTaskLand.planId": this.currentTask.id,
                    };
                    this.$axios
                        .get("/rbac/data/collectTaskLand/listPart", {
                            params,
                        })
                        .then((res) => {
                            this.localDataBase = res.data.list;
                            this.$set(this.filterObj, "streetsValue", arr);
                            this.mapFilter();
                            this.panToTown(
                                this.currentTask.treeData.list[0].administrativeName
                            );
                            loading.close();
                        })
                        .catch((err) => {
                            console.log(err);
                            loading.close();
                        });
                }, 5000);
            }

        },
    },
    //   watch: {
    //     currentTask() {
    //       this.LandParcelInfoVisible = false;
    //       let arr = [];
    //       this.currentTask.treeData.list.forEach((element) => {
    //         if (element.administrativeCode.length > 9) {
    //           arr.push(element.administrativeName);
    //         }
    //       });
    //       const loading = this.$loading({
    //         lock: true,
    //         text: "正在搜索图斑数据,请耐心等待",
    //         spinner: "el-icon-loading",
    //         background: "rgba(0, 0, 0, 0.7)",
    //       });
    //       setTimeout(() => {
    //         let params = {
    //           "collectTaskLand.planId": this.currentTask.id,
    //         };
    //         this.$axios
    //           .get("/rbac/data/collectTaskLand/listPart", {
    //             params,
    //           })
    //           .then((res) => {
    //             this.localDataBase = res.data.list;
    //             console.log(this.localDataBase);
    //             this.$set(this.filterObj, "streetsValue", arr);
    //             this.mapFilter();
    //             this.panToTown(
    //               this.currentTask.treeData.list[0].administrativeName
    //             );
    //             loading.close();
    //           })
    //           .catch((err) => {
    //             console.log(err);
    //             loading.close();
    //           });
    //       }, 2000);
    //     },
    //   },
    computed: {

        collected() {
            let temp = [];
            this.localDataBase.forEach((item) => {
                item.collectStatus === 2 ? temp.push(item.landId) : "";
            });
            return temp;
        },
        uncollected() {
            let temp = [];
            this.localDataBase.forEach((item) => {
                item.collectStatus === 1 ? temp.push(item.landId) : "";
            });
            return temp;
        },
        Allcollected() {
            let temp = [];
            this.localDataBase.forEach((item) => {
                temp.push(item.landId);
            });
            return temp;
        },
        ...mapState({
            currentTask: (state) => {
                return state.currentTask.Task.data;
            },
        }),
    },
    data() {
        return {
            position: "bottom-right",
            tk: {
                tk: tiandituToken,
            },
            randomkey:"",
            map: null,
            mapOptions: {
                center: center,
                zoom: zoom,
                style: {
                    version: 8,
                    sources: {
                        "raster-tiles": {
                            type: "raster",
                            tiles: [
                                `${serverUrl}/iserver/services/map-china400/rest/maps/${dark}/zxyTileImage.png?z={z}&x={x}&y={y}`,
                            ],
                            tileSize: 256,
                        },

                        labelLayer_img: {
                            type: "raster",
                            tiles: [
                                `${tiandituUrl}/cia_w/wmts?tk=53601310a9c2ea79748468191c57382a&service=WMTS&request=GetTile&version=1.0.0&style=default&tilematrixSet=w&format=tiles&width=256&height=256&layer=cia&tilematrix={z}&tilerow={y}&tilecol={x}`,
                            ],
                            tileSize: 256,
                        },

                        labelLayer_vec: {
                            type: "raster",
                            tiles: [
                                `${tiandituUrl}/cva_w/wmts?tk=53601310a9c2ea79748468191c57382a&service=WMTS&request=GetTile&version=1.0.0&style=default&tilematrixSet=w&format=tiles&width=256&height=256&layer=cva&tilematrix={z}&tilerow={y}&tilecol={x}`,
                            ],
                            tileSize: 256,
                        },

                        // 南海区遥感地图
                        nanhai: {
                            type: "raster",
                            tiles: [
                                `${gisUrl}/geoserver/gwc/service/wmts?SERVICE=WMTS&REQUEST=GetTile&LAYER=nanhai:nanhaiquPhase1Image&TILEMATRIX=EPSG:900913:{z}&TILEMATRIXSET=EPSG:900913&format=image%2Fpng&TileCol={x}&TileRow={y}`,
                            ],
                            tileSize: 256,
                        },
                        //图斑数据信息
                        experimentalData: {
                            type: "vector",
                            scheme: "tms",
                            tiles: [
                            `${gisUrl}/geoserver/gwc/service/tms/1.0.0/nanhai%3Aexperimental@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf`,
                                // `${gisUrl}/geoserver/gwc/service/tms/1.0.0/nanhai%3AexperimentalData@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf`,
                            ],
                        },
                    },
                    layers: [{
                            id: "raster-tiles",
                            type: "raster",
                            source: "raster-tiles",
                        },

                        {
                            id: "labelLayer_img",
                            type: "raster",
                            source: "labelLayer_img",
                        },

                        {
                            id: "labelLayer_vec",
                            type: "raster",
                            source: "labelLayer_vec",
                        },

                        {
                            id: "nanhai",
                            type: "raster",
                            source: "nanhai",
                        },

                        //图斑
                        {
                            id: `experimentalData-area-layer`,
                            source: `experimentalData`,
                            "source-layer": `experimentalData`,
                            type: "fill",
                            paint: {
                                "fill-color": fillcolor,
                                "fill-opacity": 0.5,
                            },
                        },

                        //图斑边缘
                        {
                            id: `experimentalData-line-layer`,
                            source: `experimentalData`,
                            "source-layer": `experimentalData`,
                            type: "line",
                            layout: {
                                "line-cap": "round",
                                "line-join": "round",
                            },
                            paint: {
                                "line-color": linecolor,
                            },
                        },
                    ],
                },
                renderWorldCopies: false,
                localDataBase: [],
                levelValue: false,
            },

            landCodeArray: [],
            key: 1,
            multipleSelection: [],
            audit: {
                value: "2",
                textarea: "",
            },
            auditOptions: [{
                    value: "2",
                    label: "通过",
                },
                {
                    value: "3",
                    label: "不通过",
                },
            ],
            handleEditVisible: false,
            handleAuditVisible: false,
            geojson: {
                type: "FeatureCollection",
                features: [],
            },
            mapListdialogTableVisible: false,
            mapList: [],
            villagerIndex: null,
            LandParcelInfo: {
                landCode: null,
            },
            LandParcelInfoVisible: false,
            subjectData: [],
            //地图对象，不要修改
            center: [113.02151029197415, 22.900558123212093],
            filterObj: {
                townsValue: "全部",
                streetsValue: "全部",
                figureTypeValue: "全部",
            },
            levelValue: false,
            cascaderOptionsOne: {},
            cascaderOptionsTwo: {},
            localDataBase: [],
             "experimentalData-area-layer": false
        };
    },
    methods: {
        experimentalDataAreaLayer(e) {
            if (e.target.className === 'sm-components-icon-ploygon') {
                this["experimentalData-area-layer"] = !e.target.parentNode.classList.contains('is-active')
                if (this["experimentalData-area-layer"]) {
                    this.$message({
                        message: "当前已进入图斑框选模式，无法弹出图斑采集界面",
                        type: "warning",
                        duration: 2000
                    })
                } else {
                    this.$message({
                        message: "当前已退出图斑框选模式，图斑采集工作恢复正常",
                        type: "success",
                        duration: 2000
                    })
                }
            }
        },
        getLandLocation(val) {
            let newarr = [];
            let xy = val.split(",");
            newarr.push(parseFloat(xy[0]), parseFloat(xy[1]));
            // this.mapOptions.center = newarr;
            this.mapOptions.zoom = 17;
            // this.map.panTo(this.mapOptions.center);
            this.map.zoomOut(this.mapOptions.zoom);
            // this.mapFilter();
        },
        getMyAll(collectStatus) {
            let currentTask;
            if (localStorage.getItem("currentTask/setCurrentTask")) {
                currentTask = JSON.parse(
                    localStorage.getItem("currentTask/setCurrentTask")
                );
                if (collectStatus === "已采集") {
                    collectStatus = 2;
                } else if (collectStatus === "未采集") {
                    collectStatus = 1;
                } else {
                    collectStatus = 0;
                }
                let params;
                if (collectStatus === 0) {
                    params = {
                        "collectTaskLand.planId": currentTask.data.id,
                    };
                } else {
                    params = {
                        "collectTaskLand.planId": currentTask.data.id,
                        "collectTaskLand.collectStatus": collectStatus,
                    };
                }

                return this.$axios
                    .get("/rbac/data/collectTaskLand/listPart", {
                        params,
                    })
                    .then((res) => {
                        console.log(res.data.list);
                        this.localDataBase = res.data.list || [];
                        return Promise.resolve(this.localDataBase);
                    });
            } else {
                return Promise.resolve(this.localDataBase);
            }
        },
        setFilterProperty(val) {

            console.log(val, 333333333333)
            if (localStorage.getItem("currentTask/setCurrentTask")) {
                const loading = this.$loading({
                    lock: true,
                    text: "正在搜索图斑数据,请耐心等待",
                    spinner: "el-icon-loading",
                    background: "rgba(0, 0, 0, 0.7)",
                });
                setTimeout(() => {
                    this.getMyAll(val.value).then(() => {
                        this.$set(this.filterObj, val.title, val.value);
                        this.mapFilter();
                    });
                    loading.close();
                }, 5000);
            } else {
                this.$set(this.filterObj, val.title, val.value);
                this.mapFilter();
            }
        },
        setLevel(val) {
            this.levelValue = val;
            this.mapFilter();
        },
        //图斑筛选 根据filterObj过滤图斑
        mapFilter() {
            let val = this.filterObj;
            let fil = [];
            console.log(val)
            // 镇街筛选
            val.townsValue != "全部" ? fil.push(["==", "镇街", val.townsValue]) : "";
            //村居筛选

            if (val.streetsValue instanceof Array) {
                val.streetsValue != "全部" ?
                    fil.push(["in", "村居", ...val.streetsValue]) :
                    "";
            } else {
                val.streetsValue != "全部" ?
                    fil.push(["==", "村居", val.streetsValue]) :
                    "";
            }

            if (this.collected.length) {
                // 已采集
                val.figureTypeValue == "已采集" ?
                    fil.push(["in", "DKBH", ...this.collected]) :
                    "";
            }

            if (this.uncollected.length) {
                //未采集
                val.figureTypeValue == "未采集" ?
                    fil.push(["in", "DKBH", ...this.uncollected]) :
                    "";
            }
            if (this.Allcollected.length) {
                //全部
                val.figureTypeValue == "全部" ?
                    fil.push(["in", "DKBH", ...this.Allcollected]) :
                    "";
            }
            //地块登记过滤
            this.levelValue && this.levelValue.length ?
                fil.push(["in", "二级类型", ...this.levelValue]) :
                "";
            console.log(fil)
            //设置过滤器
            if (this.map) {
                this.map.setFilter("experimentalData-line-layer", ["all", ...fil]);
                this.map.setFilter("experimentalData-area-layer", ["all", ...fil]);
            }

        },
        createArea(e) {
            //当前多边形的坐标点集合
            let current = e.features[0].geometry.coordinates[0];
            let scopeList = [];
            current.forEach((item) => {
                scopeList.push({
                    latitude: item[0],
                    longitude: item[1],
                });
            });
            let json = JSON.stringify({
                scopeList: scopeList,
            });
            //获取被框选的图斑
            let _this = this;
            axios({
                url: "https://api.leadinsight.cn/tianyan/api/v1/spot/spotCode",
                method: "post",
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                },
                data: json,
            }).then((res) => {
                let data = res.data.data;
                if (data.length > 50) {
                    _this.$message({
                        message: `框选工具最多只能选择50个图斑`,
                        type: "warning",
                    });
                    return false;
                } else if (data.length === 0) {
                    _this.$message({
                        message: `您未选择任何图斑`,
                        type: "warning",
                    });
                    return false;
                } else {
                    let landID = res.data.data;
                    let landPlanId = "";
                    if (
                        localStorage.getItem("currentTask/setCurrentTask") &&
                        this.$route.name === "MapExamine"
                    ) {
                        let currentTask = JSON.parse(
                            localStorage.getItem("currentTask/setCurrentTask")
                        );
                        landPlanId = currentTask.data.id;
                    } else {
                        _this.$message({
                            message: `您必须选择一个任务`,
                            type: "warning",
                        });
                        return false;
                    }
                    this.$axios
                        .get("rbac/data/CollectTaskLand/list", {
                            params: {
                                landCodes: landID.join(","),
                                "collectTaskLand.planId": landPlanId,
                            },
                        })
                        .then((res) => {
                            _this.mapList = res.data.list;
                            _this.toggleSelection(res.data.list);
                            _this.landCodeArray = [];
                            _this.mapListdialogTableVisible = true;
                        });
                }
            });
        },
        panToTown(value) {
            switch (value) {
                case "里水镇":
                    this.map.panTo([113.136793, 23.227369]);
                    this.mapOptions.center = [113.136793, 23.227369];
                    break;
                case "狮山镇":
                    this.map.panTo([113.012359, 23.160829]);
                    this.mapOptions.center = [113.012359, 23.160829];
                    break;
                case "大沥镇":
                    this.map.panTo([113.121615, 23.114786]);
                    this.mapOptions.center = [113.121615, 23.114786];
                    break;
                    ///////////防止眼花/////////
                case "罗村街道":
                    this.map.panTo([113.04255, 23.063944]);
                    this.mapOptions.center = [113.04255, 23.063944];
                    break;
                case "丹灶镇":
                    this.map.panTo([112.921315, 23.059877]);
                    this.mapOptions.center = [112.921315, 23.059877];
                    break;
                case "桂城街道":
                    this.map.panTo([113.183875, 23.03225]);
                    this.mapOptions.center = [113.183875, 23.03225];
                    break;
                    ///////////防止眼花/////////
                case "西樵镇":
                    this.map.panTo([112.94087, 22.93736]);
                    this.mapOptions.center = [112.94087, 22.93736];
                    break;
                case "南樵镇":
                    this.map.panTo([112.872017, 22.861839]);
                    this.mapOptions.center = [112.872017, 22.861839];
                    break;
                case "九江镇":
                    this.map.panTo([112.993321, 22.856176]);
                    this.mapOptions.center = [112.993321, 22.856176];
                    break;
                case "全部":
                    this.mapOptions.center = [113.02151029197415, 22.900558123212093];
                    break;
            }
        },
        mapLoad(e) {
            let _this = this;
            this.map = e.map;
            this.map.on("draw.create", this.createArea);
            this.map.on("click", "experimentalData-area-layer", (e) => {
                if (this["experimentalData-area-layer"]) {
                    _this.$message({
                        message: "当前已进入图斑框选模式，无法弹出图斑采集界面",
                        type: "warning",
                        duration: 2000
                    })
                    return false
                }
                e.preventDefault();
                this.randomkey = Math.random();
                console.log("e.features[0].properties:", e.features[0].properties);
                let properties = e.features[0].properties;
                _this.LandParcelInfo = properties;
                //通过图斑ID查询地块信息

                _this.$axios
                    .get("rbac/data/LandInfo/getList", {
                        params: {
                            "landInfo.landCode": _this.LandParcelInfo["DKBH"],
                            systemTypes: localStorage.getItem("SYS_TYPE"),
                        },
                    })
                    .then((res) => {

                        if (res.data.list.length > 0) {
                            //系统库有的地块
                            _this.LandParcelInfo = res.data.list[0];
                        } else {
                            //系统库没有的地块
                            _this.LandParcelInfo.landCode = _this.LandParcelInfo["DKBH"];
                            _this.LandParcelInfo.landId = _this.LandParcelInfo["DKBH"];
                            _this.LandParcelInfo.landTownCode = _this.LandParcelInfo["镇街"];
                            _this.LandParcelInfo.landVillageCode =
                                _this.LandParcelInfo["村居"];
                            _this.LandParcelInfo.landArea = _this.LandParcelInfo["AREA"];
                            _this.LandParcelInfo.landType = _this.LandParcelInfo["二级类型"];
                        }
                        _this.$set(
                            _this.LandParcelInfo,
                            "XY",
                            properties["X"] + "," + properties["Y"]
                        );

                        _this.LandParcelInfoVisible = true;
                        //查询地块关联主体生产信息 &landInfo.landCode=NHQ72689
                        _this.$axios
                            .get("rbac/data/LandSubject/get", {
                                params: {
                                    "landSubject.lsLandCode": _this.LandParcelInfo.landCode,
                                },
                            })
                            .then((res) => {
                                _this.subjectData = res.data.list;
                            });
                    });
            });
        },
        getTaskModel(obj) {
            console.log(obj);
        },
        toAddSubject() {
            console.log(1);
        },
        removeSubjectData(row) {
            this.subjectData.forEach((item, index) => {
                if (item.id === row.id) {
                    this.subjectData.splice(index, 1);
                }
            });
        },
        reloadSubject(arr) {
            this.subjectData = arr;
        },
        getLayer(mapid) {
            this.addMap(mapid);
        },
        // 地块类别
        getLandTypeList() {
            this.$axios
                .get("baseinfo/api/v1.0/fishing/landType/selectAll")
                .then((res) => {
                    this.cascaderOptionsOne = convertKey(res.data.list, {
                        landTypeName: "label",
                        landTypeCode: "value",
                    });
                });
            console.log(this.cascaderOptionsOne);
        },
        // 农产品分类
        getLandProductList() {
            this.$axios
                .get("baseinfo/api/v1.0/fishing/landTypep/productType/getList")
                .then((res) => {
                    console.log(res);
                    this.cascaderOptionsTwo = convertKey(res.data.list, {
                        productTypeName: "label",
                        productTypeCode: "value",
                    });
                });
        },
        handleChange(value) {
            this.LandParcelInfo.landType = value[value.length - 1];
        },
        handleChangeTwo(value) {
            this.LandParcelInfo.landProduct = value[value.length - 1];
        },
        toggleSelection(rows) {
            this.$nextTick(() => {
                if (rows) {
                    rows.forEach((row) => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                    this.handleSelectionChange(rows);
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            });
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(this.multipleSelection);
        },
        BatchEdit() {
            let subjectData = [];
            this.subjectData.forEach((item) => {
                subjectData.push({
                    landSubjectBase: item.subjectBase,
                    lsSubjectUseArea: item.lsSubjectUseArea ? item.lsSubjectUseArea : 0,
                    lsYearValue: item.lsYearValue ? item.lsYearValue : 0,
                    lsSubjectCode: item.subjectCode,
                });
            });

            // if (this.landCodeArray instanceof Array && this.landCodeArray.length) {
            //     console.log(this.landCodeArray)
            // } else {
            //     this.$message({
            //         type: "error",
            //         message: "系统异常，请退出重新登录",
            //     });
            //     return false;
            // }

            let plan;
            if (!localStorage.getItem("currentTask/setCurrentTask")) {
                this.$message({
                    type: "error",
                    message: "请选择对应任务",
                });
                return false;
            }
            plan = JSON.parse(localStorage.getItem("currentTask/setCurrentTask"));

            if (typeof this.LandParcelInfo.landType === "undefined") {
                this.$message({
                    type: "warning",
                    message: "地块类型必须选择",
                });
                return false;
            }

            if (typeof this.LandParcelInfo.landProduct === "undefined") {
                this.$message({
                    type: "warning",
                    message: "农产品分类必须选择",
                });
                return false;
            }

            let BatchEditObject = {
                landCodeArray: this.landCodeArray.join(","),
                landType: this.LandParcelInfo.landType,
                landProduct: this.LandParcelInfo.landProduct,
                landProduce: this.LandParcelInfo.landProduce,
                landSubjects: subjectData,
            };

            this.$axios
                .post("rbac/data/CollectTaskLand/batchEdit", {
                    params: {
                        landIds: this.landCodeArray.join(","),
                        landType: this.LandParcelInfo.landType,
                        landProduct: this.LandParcelInfo.landProduct,
                        landProduce: this.LandParcelInfo.landProduce,
                        landSubjects: subjectData,
                        planId: plan.data.id,
                    },
                })
                .then((result) => {
                    console.log(result);
                    if (result.errorCode === "00000") {
                        this.handleEditVisible = false;
                        this.$message({
                            type: "success",
                            message: "批量修改成功",
                        });
                    } else {
                        this.$message({
                            type: "error",
                            message: result.errorMsg,
                        });
                    }
                    console.log(result);
                });

            console.log(BatchEditObject);
        },
        BatchReview() {
            console.log(this.multipleSelection);
            if (this.multipleSelection.length) {
                let landIds = [];

                this.multipleSelection.forEach((item) => {
                    landIds.push(item.id);
                });

                this.$axios
                    .post("rbac/LandSubject/auditLand", {
                        params: {
                            landIds: landIds.join(","),
                            auditMemo: this.audit.textarea,
                            auditStatus: this.audit.value,
                        },
                    })
                    .then((res) => {
                        if (res.errorCode === "00000") {
                            this.$message({
                                type: "success",
                                message: "批量审核成功",
                            });
                        }
                    });
            } else {
                this.$message({
                    type: "warning",
                    message: "批量审核必须选中一条",
                });
            }
        },
        handleEdit() {
            if (this.multipleSelection.length) {
                this.multipleSelection.forEach((item) => {
                    this.landCodeArray.push(item.landId);
                });
                this.getLandTypeList();
                this.getLandProductList();
                this.handleEditVisible = true;
            } else {
                this.$message({
                    type: "warning",
                    message: "批量编辑必须选中一条",
                });
            }
        },
        handleAudit() {
            if (this.multipleSelection.length) {
                this.handleAuditVisible = true;
            } else {
                this.$message({
                    type: "warning",
                    message: "批量审核必须选中一条",
                });
            }
        },
        handleClick(row) {
            console.log(row);
            this.LandParcelInfo = row;
            this.LandParcelInfoVisible = true;
            //通过图斑ID查询地块信息
            console.log("****" + this.LandParcelInfo.landCode);
            this.$axios
                .get("rbac/data/LandInfo/getList", {
                    params: {
                        "landInfo.landCode": this.LandParcelInfo.landCode,
                    },
                })
                .then((res) => {
                    console.log(res.data.list);
                    if (res.data.list.length > 0) {
                        //系统库有的地块
                        this.LandParcelInfo = res.data.list[0];
                    }
                    // else {
                    //   //系统库没有的地块
                    //   this.LandParcelInfo.landCode = _this.LandParcelInfo['DKBH'];
                    //   this.LandParcelInfo.landTownCode = _this.LandParcelInfo['镇街'];
                    //   this.LandParcelInfo.landVillageCode = _this.LandParcelInfo['村居'];
                    //   this.LandParcelInfo.landArea = _this.LandParcelInfo.AREA;
                    //   this.LandParcelInfo.landType = _this.LandParcelInfo['二级类型'];
                    //   this.LandParcelInfo.landProduce = _this.LandParcelInfo['作物'];
                    // }
                    //查询地块关联主体生产信息 &landInfo.landCode=NHQ72689
                    this.$axios
                        .get("rbac/data/LandSubject/get", {
                            params: {
                                "landSubject.lsLandCode": this.LandParcelInfo.landCode,
                            },
                        })
                        .then((res) => {
                            console.log(res.data.list);
                            this.subjectData = res.data.list;
                        });
                });
        },
    },
};
</script>

<style lang="scss">
#map {
    height: calc(100vh - 130px);
    overflow: hidden;

    .mapboxgl-ctrl-top-left {
        transform: translateY(0%);
        border-radius: 5px;
        padding: 10px 10px 0 10px;
        background: rgba(255, 255, 255, 0.5);
        position: absolute;
        top: 600px;
        left: 20px;
        display: flex;
        width: 35px;
        flex-direction: column;

        .mapbox-gl-draw_ctrl-draw-btn {
            padding: 0;
            width: 35px;
            height: 35px;
            box-sizing: border-box;
            border: 0px;
            border-radius: 5px;
            // background-color: rgba(36, 19, 19, 0.7);
            margin-bottom: 10px;

            &:hover {
                background-color: rgba(168, 168, 168, 0.5) !important;
            }
        }

        .mapbox-gl-draw_polygon {
            background-size: 70% 70%;
        }

        .mapbox-gl-draw_trash {
            background-size: 70% 70%;
        }
    }
}

.distance-container {
    position: absolute;
    bottom: 10px;
    right: 10px;
    z-index: 1;
}

.distance-container>* {
    background-color: rgba(255, 255, 255, 0.5);
    color: #000;
    line-height: 32px;
    font-size: 32px;
    display: block;
    margin: 0;
    padding: 15px 35px;
    border-radius: 3px;
}

.examine {
    position: absolute;
    z-index: 999;
}
</style>
